package com.hhs.storage.controller;


import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.hhs.storage.bean.*;
import com.hhs.storage.service.BaseDepartmentService;
import com.hhs.storage.service.BaseUserService;
import com.hhs.storage.service.ZrAttendanceSettingService;
import com.hhs.storage.util.DateEasy;
import com.hhs.storage.util.NumberUtil;
import com.hhs.storage.util.StringUtil;
import com.sun.crypto.provider.DESCipher;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 工作时间设定前端控制器
 * </p>
 *
 * @author yuanjun
 * @since 2024-01-12
 */
@RestController
@RequestMapping("/zrSetWorkDay")
@ApiSupport(order = 1)      //排序
@Api(tags = "本周工作时间设定接口")   //
public class ZrSetWorkDayController {
    @Resource
    ZrAttendanceSettingService zrAttendanceSettingService;
    @Resource
    private HttpServletRequest request;

    /**
     * 获取表格数据
     *
     * @param workDayBean
     * @return
     */
    @RequestMapping(value = "set")
    @ApiOperation(value = "本周工作时间设定接口",
            notes = "本周工作时间设定接口",
            httpMethod = "POST"
    )
    @ApiOperationSupport(ignoreParameters = {"displayDates"})
    public ResponseBean set(WorkDayBean workDayBean) {
        LocalDate startDate = workDayBean.getStartDate();
        if (startDate == null) {
            //传空就是本周一
            startDate = DateEasy.getTimesWeekMorning().toLocalDate();
        }
        ZrAttendanceSetting zrAttendanceSetting;
        //去数据库中查找个人的大于部门的设置
        QueryWrapper<ZrAttendanceSetting> qw = new QueryWrapper<>();
        if (!"".equals(StringUtil.zNull(workDayBean.getId()))) {
            qw.eq("target_id", workDayBean.getId());
        } else {
            qw.isNull("target_id");
        }
        if (!"".equals(StringUtil.zNull(workDayBean.getType()))) {
            qw.eq("type", workDayBean.getType());
        } else {
            qw.isNull("type");
        }
        qw.eq("start_date", startDate);
        qw.orderByDesc("start_date");
        List<ZrAttendanceSetting> list = zrAttendanceSettingService.list(qw);
        if (list.size() > 0) {//找到了更新
            zrAttendanceSetting = list.get(0);
            setValue(workDayBean, startDate, zrAttendanceSetting);
            zrAttendanceSettingService.updateById(zrAttendanceSetting);
        } else {//没有找到就新增
            zrAttendanceSetting = new ZrAttendanceSetting();
            zrAttendanceSetting.setCreateDate(LocalDate.now());
            setValue(workDayBean, startDate, zrAttendanceSetting);
            zrAttendanceSettingService.save(zrAttendanceSetting);
        }
        return ResponseBean.success(null);
    }

    private void setValue(WorkDayBean workDayBean, LocalDate startDate, ZrAttendanceSetting zrAttendanceSetting) {
        zrAttendanceSetting.setStartDate(startDate);
        DateEasy da = new DateEasy(startDate);
        da.addDate(6);
        zrAttendanceSetting.setEndDate(da.toLocalDate());
        zrAttendanceSetting.setWorkType(workDayBean.getWorkType());
        if (!"".equals(StringUtil.zNull(workDayBean.getId()))) {
            zrAttendanceSetting.setTargetId(workDayBean.getId());
        }
        if (!"".equals(StringUtil.zNull(workDayBean.getType()))) {
            zrAttendanceSetting.setType(workDayBean.getType());
        }
        if (!"".equals(StringUtil.zNull(workDayBean.getWorkDaysValue())) && workDayBean.getWorkDaysValue().split(",").length == 7) {
            String[] atts = workDayBean.getWorkDaysValue().split(",");
            zrAttendanceSetting.setAtt1(Integer.parseInt(atts[0]));
            zrAttendanceSetting.setAtt2(Integer.parseInt(atts[1]));
            zrAttendanceSetting.setAtt3(Integer.parseInt(atts[2]));
            zrAttendanceSetting.setAtt4(Integer.parseInt(atts[3]));
            zrAttendanceSetting.setAtt5(Integer.parseInt(atts[4]));
            zrAttendanceSetting.setAtt6(Integer.parseInt(atts[5]));
            zrAttendanceSetting.setAtt7(Integer.parseInt(atts[6]));
        }
        if (!"".equals(StringUtil.zNull(workDayBean.getTotalHours()))) {
            zrAttendanceSetting.setTotalHours(NumberUtil.toIntCase(workDayBean.getTotalHours()));
        }
        zrAttendanceSetting.setPersonType(workDayBean.getPersonType());

    }

    @RequestMapping(value = "getWorkDay")
    @ApiOperation(value = "得到本周工作时间状态",
            notes = "得到本周工作时间状态",
            httpMethod = "POST"
    )
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, name = "id", value = "type为0时部门id，type为1时用户id", required =
                    false, paramType = "query"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "type", value = "0部门，1用户", required =
                    false, paramType = "query"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "queryType", value = "0上一周，1下一周", required =
                    false, paramType = "query"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "startDate", value = "当前修改周周一时间，不传代表本周，上一周下一周时要从前台再传过来", required =
                    false, paramType = "query"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "personType", value = "0普通用户，1领导，如果id,type为空则为领导分类的总设置", required =
                    false, paramType = "query"),
    })
    public ResponseBean<WorkDayBean> getWorkDay(@ApiIgnore InputParam inputParam) {
        LocalDate startDate = inputParam.getStartDate();
        if (startDate == null) {//传空就是本周一
            startDate = DateEasy.getTimesWeekMorning().toLocalDate();
        }
        if (inputParam.getQueryType() != null && inputParam.getQueryType() == 0) {//上周一
            DateEasy da = new DateEasy(startDate);
            da.addDate(-7);
            startDate = da.toLocalDate();
        }
        if (inputParam.getQueryType() != null && inputParam.getQueryType() == 1) {//下周一
            DateEasy da = new DateEasy(startDate);
            da.addDate(7);
            startDate = da.toLocalDate();
        }
        //得到部门或用户最后一次的设置情况
        QueryWrapper<ZrAttendanceSetting> qw = new QueryWrapper<>();
        if (!"".equals(StringUtil.zNull(inputParam.getId()))) {
            qw.eq("target_id", inputParam.getId());
        } else {
            qw.isNull("target_id");
        }
        if (!"".equals(StringUtil.zNull(inputParam.getType()))) {
            qw.eq("type", inputParam.getType());
        } else {
            qw.isNull("type");
        }
        qw.le("start_date", startDate);
        qw.orderByDesc("start_date");
        List<ZrAttendanceSetting> list = zrAttendanceSettingService.list(qw);
        ZrAttendanceSetting listSetting;
        //如果有取到
        WorkDayBean p;
        if (list.size() > 0) {
            listSetting = list.get(0);
            //设置startDate
            listSetting.setStartDate(startDate);
            p = WorkDayBean.zrAttendanceSettingToWorkDayBean(listSetting);
        } else {//没有取到
            listSetting = ZrAttendanceSetting.getInstanceDefault(inputParam);
            //设置startDate
            listSetting.setStartDate(startDate);
            p = WorkDayBean.zrAttendanceSettingToWorkDayBean(listSetting);
        }
        ResponseBean res = ResponseBean.success(p);
        return res;
    }

    @RequestMapping(value = "goWorkDay")
    @ApiOperation(value = "直接到设定的工作时间",
            notes = "直接到设定的工作时间",
            httpMethod = "POST"
    )
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, name = "id", value = "type为0时部门id，type为1时用户id", required =
                    false, paramType = "query"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "type", value = "0部门，1用户", required =
                    false, paramType = "query"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "personType", value = "0普通用户，1领导，如果id,type为空则为领导分类的总设置", required =
                    false, paramType = "query"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "goDate", value = "直接到设定的时间", required =
                    false, paramType = "query"),
    })
    public ResponseBean<WorkDayBean> goWorkDay(@ApiIgnore InputParam inputParam) {
        DateEasy morning = DateEasy.getTimesWeekMorning(new DateEasy(inputParam.getGoDate()));
        QueryWrapper<ZrAttendanceSetting> qw = new QueryWrapper<>();
        if (!"".equals(StringUtil.zNull(inputParam.getId()))) {
            qw.eq("target_id", inputParam.getId());
        } else {
            qw.isNull("target_id");
        }
        if (!"".equals(StringUtil.zNull(inputParam.getType()))) {
            qw.eq("type", inputParam.getType());
        } else {
            qw.isNull("type");
        }
        qw.le("start_date", morning.toLocalDate());
        qw.orderByDesc("start_date");
        List<ZrAttendanceSetting> list = zrAttendanceSettingService.list(qw);
        if (list.size() > 0) {
            ZrAttendanceSetting zas = list.get(0);
            WorkDayBean wkb = WorkDayBean.zrAttendanceSettingToWorkDayBean(zas);
            return ResponseBean.success(wkb);
        } else {
            WorkDayBean wkb = WorkDayBean.getInstanceDefault(inputParam);
            return ResponseBean.success(wkb);
        }
    }

    @RequestMapping(value = "table")
    @ApiOperation(value = "考勤设置列表",
            notes = "考勤设置列表",
            httpMethod = "POST"
    )
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, name = "id", value = "type为0时部门id，type为1时用户id,id,type同时空为部门领导统一设置接口", required =
                    false, paramType = "query"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "type", value = "0部门，1用户", required =
                    false, paramType = "query"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "page", value = "页", required =
                    true, paramType = "query"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "size", value = "页大小", required =
                    true, paramType = "query"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "startDate", value = "开始日期，用于搜索", required =
                    false, paramType = "query"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "endDate", value = "结束日期，用于搜索", required =
                    false, paramType = "query")
    })
    public ResponseBeanPage<ZrAttendanceSetting> table(@ApiIgnore InputParam inputParam) {
        QueryWrapper<ZrAttendanceSetting> qw = new QueryWrapper<>();
        if (!"".equals(StringUtil.zNull(inputParam.getId()))) {
            qw.eq("target_id", inputParam.getId());
        } else {
            qw.isNull("target_id");
        }
        if (!"".equals(StringUtil.zNull(inputParam.getType()))) {
            qw.eq("type", inputParam.getType());
        } else {
            qw.isNull("type");
        }
        if (inputParam.getStartDate()!=null) {
            qw.ge("start_date", inputParam.getStartDate());
        }
        if (inputParam.getEndDate()!=null) {
            qw.le("end_date", inputParam.getEndDate());
        }
        qw.orderByDesc("start_date");
        Page<ZrAttendanceSetting> page=zrAttendanceSettingService.page(new Page(inputParam.getPage(),inputParam.getSize()),qw);
        ResponseBeanPage res=ResponseBeanPage.getInstance();
        res.setTotal(page.getTotal());
        res.setCode(1);
        //处理行
        for (ZrAttendanceSetting zr :
                page.getRecords()) {
            if(zr.getWorkType()==4){
                zr.setAtt1(null);
                zr.setAtt2(null);
                zr.setAtt3(null);
                zr.setAtt4(null);
                zr.setAtt5(null);
                zr.setAtt6(null);
                zr.setAtt7(null);
            }else{
                zr.setTotalHours(null);
            }
        }
        res.setRows(page.getRecords());
        return res;
    }
    @RequestMapping(value = "delete")
    @ApiOperation(value = "考勤设置列表删除",
            notes = "考勤设置列表删除",
            httpMethod = "POST"
    )
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, name = "id", value = "考勤设置列表id,','可以分开多个", required =
                    true, paramType = "query")
    })
    public ResponseBean<String> delete(@ApiIgnore InputParam inputParam){
        if(StringUtil.iszNull(inputParam.getId())){
            return ResponseBean.error("参数错误");
        }
        String[] ids = inputParam.getId().split(",");
        zrAttendanceSettingService.removeByIds(Arrays.asList(ids));
        return ResponseBean.success(null);
    }
    @RequestMapping(value = "getById")
    @ApiOperation(value = "考勤设置列表用Id读取",
            notes = "考勤设置列表用Id读取",
            httpMethod = "POST"
    )
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, name = "id", value = "考勤设置列表id", required =
                    true, paramType = "query")
    })
    public ResponseBean<WorkDayBean> getById(@ApiIgnore InputParam inputParam){
        if(StringUtil.iszNull(inputParam.getId())){
            return ResponseBean.error("参数错误");
        }
        ZrAttendanceSetting z = zrAttendanceSettingService.getById(inputParam.getId());
        WorkDayBean workDayBean = WorkDayBean.zrAttendanceSettingToWorkDayBean(z);
        return ResponseBean.success(workDayBean);
    }
}

